/**
 * 管理 shop 功能模块的相关状态的vuex数据
 */
import {
  reqShopInfo,
  reqShopScore,
  reqShopGoods
} from '../../api'
import {
  RECEIVE_SHOPGOODS,
  RECEIVE_SHOPINFO,
  RECEIVE_SHOPSCORE,
  ADD_FOOD_COUNT,
  SUB_FOOD_COUNT,
  CLEAR_CART
} from '../mutations-types'
import Vue from 'vue'

const state = {
  shop_goods: [], //商品
  shop_score: [], // 评价
  shop_merchants: {}, // 商家
  cartFood: [] // 购物车内的食物
}

const mutations = {
  [RECEIVE_SHOPGOODS](state, goods) {
    state.shop_goods = goods
  },
  [RECEIVE_SHOPINFO](state, info) {
    state.shop_merchants = info
  },
  [RECEIVE_SHOPSCORE](state, score) {
    state.shop_score = score
  },

  [ADD_FOOD_COUNT](state, {food}) {
    if(food.count){
      food.count ++
    }else{
      // 这样设置不是响应式的属性
      // food.count = 1
      // 设置响应式的属性
      Vue.set(food, "count", 1)
      state.cartFood.push(food)
    }
  },

  [SUB_FOOD_COUNT](state, {food}) {
    if(food.count > 0){
      food.count --
      if(food.count === 0){
        // 只会遍历购物车内的商品，不会遍历整个food商品
        state.cartFood.splice(state.cartFood.indexOf(food), 1)
      }
    }
  },

  [CLEAR_CART](state) {
    // 在清空之前要确认购物车所有的数量都为空
    state.cartFood.forEach((item) => {
      item.count = 0
    })
    // 清空cart的状态
    state.cartFood = []
  },
}

const actions = {
  async getShopGoods({
    commit
  }) {
    const result = await reqShopGoods()
    if (result.code === 0) {
      const goods = result.data
      commit(RECEIVE_SHOPGOODS, goods)
    }
  },
  async getShopScore({
    commit
  }) {
    const result = await reqShopScore()
    if (result.code === 0) {
      const score = result.data
      commit(RECEIVE_SHOPSCORE, score)
    }
  },
  async getShopInfo({
    commit
  }) {
    const result = await reqShopInfo()
    if (result.code === 0) {
      const info = result.data
      commit(RECEIVE_SHOPINFO, info)
    }
  },
  
  // 当前食物的数量增加
  addFoodCount({commit}, {food}){
    commit(ADD_FOOD_COUNT, {food})
  },

  // 当前食物的重量减少
  subFoodCount({commit}, {food}){
    commit(SUB_FOOD_COUNT, {food})
  },

  clearCart({commit}){
    commit(CLEAR_CART)
  }
}

const getters = {
  // 总评论数
  totalRatingsCount(){
    return state.shop_score.length
  },

  // 推荐的评论数
  positiveRatingsCount(){
    // let count = 0
    // state.shop_score.forEach((item) => {
    //   if(item.rateType === 0){
    //     count ++
    //   }
    // })
    return (state.shop_score.filter(item => item.rateType === 0)).length
    // return count
  },

  // 商品总价格
  totalPrice(){
    return state.cartFood.reduce((pre, food) => pre + (food.count * food.price) ,0)
  },

  // 商品总数量
  totalNum(){;
    return state.cartFood.reduce((pre, food) => pre + food.count ,0)
  }

}

export default {
  state,
  mutations,
  actions,
  getters
}
